package com.jianchunxc.pj.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class DefaultGoodsDao implements GoodsDao {
    @Autowired
    private DataSource dataSource;

    @Override
    public List<Map<String, Object>> findGoods() {
        //获取连接
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        String sql = "select * from tb_goods";
        try {
            List<Map<String, Object>> list = new ArrayList<>();
            connection=dataSource.getConnection();
            statement=connection.createStatement();
            resultSet=statement.executeQuery(sql);
            while (resultSet.next()) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", resultSet.getInt("id"));
                map.put("name", resultSet.getString("name"));
                map.put("remark", resultSet.getString("remark"));
                map.put("createdTime", resultSet.getTimestamp("createdTime"));
                list.add(map);
            }
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            if(resultSet!=null)try{resultSet.close();}catch (SQLException e1){}
            if(statement!=null)try{statement.close();}catch (SQLException e2){}
            if (connection!=null)try{connection.close();}catch (SQLException e3){}
        }

    }
}
